<template>
  <div class="user-manage-page">
    <div class="search-wrapper">
      <div class="title-wrapper">
        <span class="title">用户筛选</span>
      </div>
      <div class="content-wrapper">
        <div class="search-item">
          <span class="item-label">组织结构</span>
          <el-select
            class="item-input"
            v-model="queryObj.ogaCode"
            placeholder="请选择组织结构"
            clearable
            @change="searchHandle"
          >
            <el-option
              v-for="item in ogaList"
              :key="item.id"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </div>
        <div class="search-item">
          <span class="item-label">用户名</span>
          <el-input
            class="item-input"
            v-model="queryObj.name"
            placeholder="请输入用户名"
            clearable
            @change="searchHandle"
          />
        </div>
        <div class="search-btn" @click="searchHandle">筛选</div>
        <div class="add-btn" @click="addHandle">新增</div>
      </div>
    </div>
    <div class="data-wrapper">
      <div class="title-wrapper">
        <span class="title">用户列表</span>
      </div>
      <div class="table-wrapper">
        <el-table
          :data="tableData"
          stripe
          fit
          class="self-stripe-table"
          height="100%"
        >
          <el-table-column type="index" label="序号" width="100" />
          <el-table-column prop="name" label="用户名" />
          <el-table-column label="组织结构">
            <template #default="scope">
              <div>{{ scope.row.organization?.name || "--" }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="userCode" label="用户编码" />
          <el-table-column label="角色">
            <template #default="scope">
              <div>
                {{
                  scope.row.roles.map((item: any) => item.name).join(",") ||
                  "--"
                }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150" align="left">
            <template #default="scope">
              <div
                class="table-btn"
                :class="scope.row.defaultUser ? 'disabled' : ''"
                @click="scope.row.defaultUser ? null : editHandle(scope.row)"
              >
                编辑
              </div>
              <div class="table-btn" @click="deleteHandle(scope.row)">删除</div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="pagination.totalPages > 1" class="pagination-wrapper">
      <el-pagination
        v-model="pagination.page"
        :total="pagination.totalElements"
        :page-size="pagination.size"
        background
        :hide-on-single-page="true"
        @size-change="sizeChangeHandle"
        @current-change="currentChangeHandle"
      />
    </div>

    <!-- 添加用户弹框 -->
    <el-dialog
      class="self-dialog"
      v-model="addDialogVisible"
      title="添加用户"
      width="50%"
      @close="resetAddForm"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="addFormRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="用户名" prop="name">
          <el-input
            v-model="addForm.name"
            placeholder="请输入用户名"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="用户编码" prop="userCode">
          <el-input
            :disabled="!!addForm.id"
            v-model="addForm.userCode"
            placeholder="请输入用户编码"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="组织结构" prop="ogaCode">
          <el-select
            v-model="addForm.ogaCode"
            placeholder="请选择组织结构"
            clearable
          >
            <el-option
              v-for="item in ogaList"
              :key="item.id"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="角色" prop="roleIds">
          <el-select
            v-model="addForm.roleIds"
            placeholder="请选择角色"
            style="width: 100%"
            multiple
            clearable
          >
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="submitAddForm"
            :loading="addFormLoading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import JSEncrypt from "jsencrypt";
import {
  getUserListAPI,
  deleteUserAPI,
  registerAPI,
  updateUserAPI,
  UserType,
  RegisterType,
  UpdateUserType,
} from "@/api/service/user";
import { getRoleListAPI, RoleType } from "@/api/service/role";
import { getOgaListAPI, OgaType } from "@/api/service/oga";
import { getPublicKeyAPI } from "@/api/service/user";
import { ListResponseType, PaginationType } from "@/api/globalType";

// 查询条件
const queryObj = ref({
  name: "",
  ogaCode: "",
});

// 分页
const pagination = ref<PaginationType>({
  page: 1,
  size: 50,
  totalElements: 0,
  totalPages: 0,
});

// 表格数据
const tableData = ref<UserType[]>([]);
// API调用保护状态
const listApiLoading = ref(false);

// 页面初始化
onMounted(() => {
  loadRoleList();
  loadUserList();
});
// 获取角色列表
const roleList = ref<RoleType[]>([]);
const roleMap = ref<Record<string, string>>({});
const roleListApiLoading = ref(false);
const loadRoleList = async () => {
  try {
    roleListApiLoading.value = true;
    const response = await getRoleListAPI();
    roleList.value = response as any as RoleType[];
    roleList.value?.forEach((item) => {
      roleMap.value[item.id] = item.name;
    });
  } catch (error) {
    ElMessage.error("获取角色列表失败");
    console.error("Load role list error:", error);
  } finally {
    roleListApiLoading.value = false;
  }
};

// 获取组织结构列表
const ogaList = ref<OgaType[]>([]);
const ogaMap = ref<Record<string, string>>({});
const ogaListApiLoading = ref(false);
const loadOgaList = async () => {
  try {
    if (ogaListApiLoading.value) return;
    ogaListApiLoading.value = true;

    const response = await getOgaListAPI();
    const result = response as any as OgaType[];
    if (result) {
      ogaList.value = result || [];
      ogaList.value?.forEach((item) => {
        ogaMap.value[item.code] = item.name;
      });
    }
  } catch (error) {
    ElMessage.error("获取组织列表失败");
    console.error("Load oga list error:", error);
  } finally {
    ogaListApiLoading.value = false;
  }
};
loadOgaList();

// 加载用户列表
const loadUserList = async () => {
  try {
    listApiLoading.value = true;
    const params = {
      name: queryObj.value.name || undefined,
      ogaCode: queryObj.value.ogaCode || undefined,
      page: pagination.value.page,
      size: pagination.value.size,
    };

    const response = await getUserListAPI(params);
    const result = response as any as ListResponseType<UserType>;
    if (result) {
      tableData.value = result.content || [];
      pagination.value.totalPages = result.totalPages || 0;
      pagination.value.totalElements = result.totalElements || 0;
      pagination.value.page = result.page || 1;
      pagination.value.size = result.size || 50;
    }
  } catch (error) {
    ElMessage.error("获取用户列表失败");
    console.error("Load user list error:", error);
  } finally {
    listApiLoading.value = false;
  }
};

// 搜索
const searchHandle = () => {
  pagination.value.page = 1; // 重置到第一页
  loadUserList();
};

// 分页大小改变
const sizeChangeHandle = (size: number) => {
  pagination.value.size = size;
  pagination.value.page = 1;
  loadUserList();
};

// 当前页改变
const currentChangeHandle = (page: number) => {
  pagination.value.page = page;
  loadUserList();
};

const publicKey = ref("");
// 获取公钥
const getPublicKey = async () => {
  try {
    const response = await getPublicKeyAPI();
    publicKey.value = response as any;
  } catch (error) {
    ElMessage.error("获取加密密钥失败");
  }
};
getPublicKey();

// 密码加密
const encryptPassword = (password: string) => {
  if (!publicKey.value) {
    ElMessage.error("加密密钥未获取");
    return "";
  }

  const encrypt = new JSEncrypt();
  encrypt.setPublicKey(publicKey.value);
  return encrypt.encrypt(password) || "";
};

// 添加用户
const addDialogVisible = ref(false);
const addFormRef = ref();
const addFormLoading = ref(false);

function addHandle() {
  addDialogVisible.value = true;
  // 等待DOM更新后清除验证状态
  nextTick(() => {
    addFormRef.value?.clearValidate();
  });
}

// 编辑用户
function editHandle(row: any) {
  addDialogVisible.value = true;
  addForm.value = {
    id: row.id,
    name: row.name,
    userCode: row.userCode,
    ogaCode: row.organization?.code || "",
    roleIds: row.roles.map((item: any) => item.id),
  };
  // 等待DOM更新后清除验证状态
  nextTick(() => {
    addFormRef.value?.clearValidate();
  });
}
// 添加表单数据
const addForm = ref({
  id: "",
  name: "",
  userCode: "",
  ogaCode: "",
  roleIds: [],
});

// 表单验证规则 - 设置为手动触发，避免弹框打开时就显示错误
const addFormRules = {
  name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  userCode: [{ required: true, message: "请输入用户编码", trigger: "blur" }],
};

// 重置添加表单
function resetAddForm() {
  addForm.value = {
    id: "",
    name: "",
    userCode: "",
    ogaCode: "",
    roleIds: [],
  };
  addFormRef.value?.clearValidate();
}

// 提交添加表单
function submitAddForm() {
  // 防止并发提交
  if (addFormLoading.value) return;

  addFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 加密密码
        const encryptedPassword = encryptPassword(
          `${addForm.value.userCode}@qidi`
        );
        if (!encryptedPassword) {
          addFormLoading.value = false;
          return;
        }

        if (addForm.value.id) {
          const updateData: UpdateUserType = {
            userCode: addForm.value.userCode,
            name: addForm.value.name,
            ogaCode: addForm.value.ogaCode,
            roleIds: addForm.value.roleIds,
          };
          await updateUserAPI(updateData);
        } else {
          const registerData: RegisterType = {
            name: addForm.value.name,
            userCode: addForm.value.userCode,
            encryptedPassword,
            ogaCode: addForm.value.ogaCode,
            roleId: addForm.value.roleIds[0],
          };
          await registerAPI(registerData);
        }

        ElMessage.success("添加成功");

        resetAddForm();
        // 刷新列表
        pagination.value.page = 1;
        loadUserList();
      } catch (error: any) {
        if (error) {
          ElMessage.error(error);
        } else {
          ElMessage.error("添加失败，请检查网络连接");
        }
      } finally {
        addFormLoading.value = false;
      }
    }
  });
}

// 删除用户
function deleteHandle(row: UserType) {
  ElMessageBox.confirm("确定删除该用户吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteUserAPI(row.id)
      .then(() => {
        ElMessage.success("删除用户成功");
        loadUserList();
      })
      .catch(() => {
        ElMessage.error("删除用户失败");
      });
  });
}
</script>

<style scoped lang="scss">
.user-manage-page {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.title-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  min-height: 2rem;
  padding-left: 1rem;
  color: $color_brand;
  font-size: $font-size-block-title;
}
.title-wrapper::before {
  position: absolute;
  left: 0;
  top: 50%;
  display: block;
  content: "";
  width: 0.5rem;
  height: 0.5rem;
  border-radius: 50%;
  background-color: $color_brand;
  transform: translateY(-50%);
}
.search-wrapper {
  background-color: #fff;
  flex-shrink: 0;
  padding: 1.5rem;
  border-bottom: 1px solid $border-color-primary;
  .content-wrapper {
    position: relative;
    display: flex;
    padding: 2rem 2rem 0 2rem;
  }
  .search-item {
    display: flex;
    align-items: center;
    padding-right: 2rem;
    .item-label {
      display: inline;
      padding-right: 1rem;
      flex-wrap: nowrap;
      text-align: right;
      color: $text-color-regular;
    }
    .item-input {
      width: 20rem;
    }
  }
  .search-btn {
    display: flex;
    align-items: center;
    padding: 0 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
  .add-btn {
    position: absolute;
    right: 3.2rem;
    top: 2rem;
    display: flex;
    align-items: center;
    padding: 0.5rem 1.5rem;
    background-color: $color_brand;
    color: #fff;
    border-radius: 0.5rem;
    cursor: pointer;
  }
}
.data-wrapper {
  flex: 1;
  min-height: 0;
  display: flex;
  flex-direction: column;
  padding: 1.5rem;
  background-color: #fff;
  .table-wrapper {
    padding: 0 2rem;
    flex: 1;
    min-height: 0;
    margin-top: 1.5rem;
  }
  .table-btn {
    display: inline-flex;
    align-items: center;
    background-color: $color_brand;
    color: #fff;
    margin-left: 0.5rem;
    padding: 0 1rem;
    border-radius: 0.5rem;
    font-size: $font-size-base-btn-text;
    cursor: pointer;
    &.disabled {
      background-color: $text-color-disabled;
      border: 1px solid $text-color-disabled;
      cursor: not-allowed;
    }
  }
  .table-btn:first-child {
    margin-left: 0;
  }
  .table-btn:hover {
    text-decoration: underline;
  }
  .signal-status.normal {
    color: $color_success;
  }
  .signal-status.abnormal {
    color: $color_danger;
  }
}

// 分页区域样式
.pagination-wrapper {
  flex-shrink: 0;
}

// 设置宽高16:9
:deep(.el-dialog) {
  margin-top: 3rem !important;
}
</style>
